import os

import fitz
from PIL import Image
import subprocess

from app.project.doc_to_recommendation.utils.log_utils import get_logger


def load_pdf_page(page, dpi):
    pix = page.get_pixmap(matrix=fitz.Matrix(dpi/72, dpi/72))
    image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
    if pix.width > 3000 or pix.height > 3000:
        pix = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)
        image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
    return image

def load_pdf(pdf_path, dpi=144):
    images = []
    doc = fitz.open(pdf_path)
    for i in range(len(doc)):
        page = doc[i]
        image = load_pdf_page(page, dpi)
        images.append(image)
    return images

def load_ppt(ppt_path, libreoffice_path='libreoffice', time_out=20, retry=5):
    def do_convert(cmd, t_out):
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        r_code = p.wait(t_out * 1000)
        return r_code
    log = get_logger(__name__)
    log.info(f"pptx2pdf开始，libreoffice_path: {libreoffice_path}, time_out: {time_out}")
    path = os.path.dirname(ppt_path)
    file_name = os.path.splitext(os.path.basename(ppt_path))[0]
    pdf_full_name = os.path.join(path, f'{file_name}.pdf')
    command = f"{libreoffice_path}  --headless  --convert-to pdf --outdir {path} {ppt_path} "
    ret_code = do_convert(command, time_out)
    if ret_code != 0:
        p_try = retry
        log.error(f"pptx2pdf转换失败，响应码：{ret_code}, 重试次数剩余：{p_try}")
        while p_try > 0:
            ret_code = do_convert(command, time_out)
            if ret_code == 0:
                break
            p_try = p_try - 1
            log.error(f"pptx2pdf转换失败，响应码：{ret_code}, 重试次数剩余：{p_try}")
            if p_try <= 0:
                raise RuntimeError(f"pptx2pdf转换失败，重试次数耗尽，最后一次响应码：{ret_code}")
    log.info(f"pptx2pdf转换完成，gen_file_path: {pdf_full_name}")
    result = load_pdf(pdf_full_name)
    os.remove(pdf_full_name)
    return result

if __name__ == '__main__':
    images = load_ppt("C:\\Users\\18326\\Desktop\\WORKSTUFF\\产品推荐-总（试点系统）\\《信息科技管理系统产品推荐手册》2025年4月28日.pptx")
    images[4].show()
